package net.j4love.dubbo.serialize;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author He Peng
 * @create 2017-05-29 0:12
 * @update 2017-05-29 0:12
 * @updatedesc : 更新说明
 * @see
 */
public class HessianSerialize {

    public static void main(String[] args) throws IOException {

        Student student = new Student();
        List<Hobby> hobbies = new ArrayList<>();
        hobbies.add(new Hobby().setDesc("学英语"));
        hobbies.add(new Hobby().setDesc("玩游戏"));
        hobbies.add(new Hobby().setDesc("打篮球"));
        hobbies.add(new Hobby().setDesc("吐槽"));

        student.setName("小明")
                .setAge(12)
                .setGender("男")
                .setHobbies(hobbies);


        byte[] bytes = serialize(student);
        System.err.println("byte size : " + bytes.length); // 319

        Object obj = deserialize(bytes);

        if (student.equals(obj)) {
            System.err.println(obj);
        }
    }

    public static byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(byteOutStream);
        hessianOutput.writeObject(object);
        return byteOutStream.toByteArray();
    }

    public static Object deserialize(byte[] bytes) throws IOException {
        ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes);
        HessianInput hessianInput = new HessianInput(byteInStream);
        return hessianInput.readObject();
    }
}
